import asyncio
import aiohttp
from flask import Flask, jsonify
import time
import logging.config


LOGGING_CONFIG = {
    "version": 1,
    "formatters": {
        "default": {
            'format': '%(asctime)s %(filename)s %(lineno)s %(levelname)s thread:%(thread)d %(message)s',
        }
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "level": logging.DEBUG,
            "formatter": "default",
        }
    },
    "loggers": {
        "console_logger": {
            "handlers": ["console"],
            "level": "DEBUG",
            "propagate": False,
        }
    },

    "disable_existing_loggers": True,
}

logging.config.dictConfig(LOGGING_CONFIG)

#指定使用哪个logger
logger = logging.getLogger("console_logger")

def create_app() -> Flask:
    app = Flask(__name__)
    # 在flask应用上下文环境下的初始化操作
    with app.app_context():
        ...
    return app

app =create_app()

async def fetch_data(url):
    logger.debug("start async io")
    await asyncio.sleep(1)
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            logger.debug("received data")
            return await response.json()
# http://localhost:5600/api/data
@app.route('/api/data', methods=['GET'])
async def get_data():
    url ="http://httpbin.org/get"
    tasks = [fetch_data(url) for _ in range(3)] # 创建3个任务
    results = await asyncio.gather(*tasks) # 并发执行任务
    logger.debug(results)
    return jsonify(results)


if __name__ =='__main__':
    app.run(debug=True,port=5600)